// components/wechat-notification/wechat-notification.js
const { request } = require('../../utils/request')
const { formatTime } = require('../../utils/util')

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    userInfo: {
      type: Object,
      value: {}
    },
    theme: {
      type: String,
      value: 'admin'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    notificationEnabled: true,
    notificationTypes: [
      {
        id: 'capsule_created',
        name: '胶囊创建',
        description: '创建记忆胶囊时通知',
        enabled: true,
        icon: '💊',
        color: '#667eea'
      },
      {
        id: 'capsule_opened',
        name: '胶囊开启',
        description: '胶囊到达开启时间时通知',
        enabled: true,
        icon: '⏰',
        color: '#f093fb'
      },
      {
        id: 'mood_recorded',
        name: '心情记录',
        description: '记录心情时通知对方',
        enabled: true,
        icon: '💝',
        color: '#ff6b9d'
      },
      {
        id: 'thief_activated',
        name: '心情小偷',
        description: '心情被偷时通知',
        enabled: true,
        icon: '😈',
        color: '#ffa726'
      },
      {
        id: 'period_reminder',
        name: '生理期提醒',
        description: '生理期相关提醒',
        enabled: true,
        icon: '🌸',
        color: '#ff8a80'
      },
      {
        id: 'daily_summary',
        name: '每日总结',
        description: '每日情感总结',
        enabled: false,
        icon: '📊',
        color: '#4ecdc4'
      },
      {
        id: 'weekly_report',
        name: '周报',
        description: '每周情感报告',
        enabled: false,
        icon: '📈',
        color: '#45b7d1'
      },
      {
        id: 'achievement_unlocked',
        name: '成就解锁',
        description: '解锁新成就时通知',
        enabled: true,
        icon: '🏆',
        color: '#ffd93d'
      }
    ],
    notificationHistory: [],
    loading: false,
    showSettings: false,
    showHistory: false
  },

  /**
   * 组件生命周期函数
   */
  lifetimes: {
    attached() {
      this.loadNotificationSettings()
      this.loadNotificationHistory()
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 加载通知设置
     */
    async loadNotificationSettings() {
      try {
        const response = await request.get('/api/notifications/settings')
        if (response.code === 200) {
          const settings = response.data
          this.setData({
            notificationEnabled: settings.enabled || true,
            'notificationTypes': this.data.notificationTypes.map(type => ({
              ...type,
              enabled: settings[type.id] !== undefined ? settings[type.id] : type.enabled
            }))
          })
        }
      } catch (error) {
        console.error('加载通知设置失败:', error)
      }
    },

    /**
     * 加载通知历史
     */
    async loadNotificationHistory() {
      try {
        const response = await request.get('/api/notifications/history', {
          page: 1,
          size: 20
        })
        if (response.code === 200) {
          this.setData({
            notificationHistory: response.data.records.map(item => ({
              ...item,
              timeText: formatTime(new Date(item.createTime)),
              typeText: this.getNotificationTypeText(item.type)
            }))
          })
        }
      } catch (error) {
        console.error('加载通知历史失败:', error)
      }
    },

    /**
     * 获取通知类型文本
     */
    getNotificationTypeText(type) {
      const typeMap = {
        'capsule_created': '创建记忆胶囊',
        'capsule_opened': '胶囊开启提醒',
        'mood_recorded': '心情记录通知',
        'thief_activated': '心情小偷提醒',
        'period_reminder': '生理期提醒',
        'daily_summary': '每日情感总结',
        'weekly_report': '每周情感报告',
        'achievement_unlocked': '成就解锁通知'
      }
      return typeMap[type] || '未知通知'
    },

    /**
     * 切换通知开关
     */
    async toggleNotification(e) {
      const enabled = e.detail.value
      this.setData({ notificationEnabled: enabled })
      
      try {
        await request.post('/api/notifications/settings', {
          enabled: enabled
        })
        
        wx.showToast({
          title: enabled ? '通知已开启' : '通知已关闭',
          icon: 'success'
        })
      } catch (error) {
        console.error('更新通知设置失败:', error)
        wx.showToast({
          title: '设置更新失败',
          icon: 'none'
        })
        this.setData({ notificationEnabled: !enabled })
      }
    },

    /**
     * 切换通知类型开关
     */
    async toggleNotificationType(e) {
      const { type } = e.currentTarget.dataset
      const enabled = e.detail.value
      
      const types = this.data.notificationTypes.map(item =>
        item.id === type ? { ...item, enabled } : item
      )
      this.setData({ notificationTypes: types })
      
      try {
        await request.post('/api/notifications/settings', {
          [type]: enabled
        })
        
        wx.showToast({
          title: enabled ? '已开启' : '已关闭',
          icon: 'success'
        })
      } catch (error) {
        console.error('更新通知类型失败:', error)
        wx.showToast({
          title: '设置更新失败',
          icon: 'none'
        })
        
        const revertTypes = this.data.notificationTypes.map(item =>
          item.id === type ? { ...item, enabled: !enabled } : item
        )
        this.setData({ notificationTypes: revertTypes })
      }
    },

    /**
     * 发送测试通知
     */
    async sendTestNotification(e) {
      const { type } = e.currentTarget.dataset
      
      try {
        const response = await request.post('/api/notifications/test', {
          type: type,
          userId: this.properties.userInfo.id
        })
        
        if (response.code === 200) {
          wx.showToast({
            title: '测试通知已发送',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: response.message || '发送失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('发送测试通知失败:', error)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    },

    /**
     * 显示设置面板
     */
    showSettingsPanel() {
      this.setData({ showSettings: true })
    },

    /**
     * 隐藏设置面板
     */
    hideSettingsPanel() {
      this.setData({ showSettings: false })
    },

    /**
     * 显示历史面板
     */
    showHistoryPanel() {
      this.setData({ showHistory: true })
      this.loadNotificationHistory()
    },

    /**
     * 隐藏历史面板
     */
    hideHistoryPanel() {
      this.setData({ showHistory: false })
    },

    /**
     * 绑定微信服务号
     */
    async bindWechatService() {
      try {
        const response = await request.post('/api/wechat/bind-service')
        if (response.code === 200) {
          wx.showModal({
            title: '绑定成功',
            content: '微信服务号已绑定，现在可以接收通知了',
            showCancel: false
          })
        } else {
          wx.showModal({
            title: '绑定失败',
            content: response.message || '请稍后再试',
            showCancel: false
          })
        }
      } catch (error) {
        console.error('绑定微信服务号失败:', error)
        wx.showModal({
          title: '网络错误',
          content: '请检查网络连接',
          showCancel: false
        })
      }
    },

    /**
     * 一键开启所有通知
     */
    async enableAllNotifications() {
      try {
        wx.showLoading({ title: '开启中...' })
        
        const settings = {}
        this.data.notificationTypes.forEach(type => {
          settings[type.id] = true
        })
        settings.enabled = true
        
        await request.post('/api/notifications/settings', settings)
        
        this.setData({
          notificationEnabled: true,
          'notificationTypes': this.data.notificationTypes.map(type => ({
            ...type,
            enabled: true
          }))
        })
        
        wx.hideLoading()
        wx.showToast({
          title: '所有通知已开启',
          icon: 'success'
        })
      } catch (error) {
        console.error('开启所有通知失败:', error)
        wx.hideLoading()
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    }
  }
})